package nyist.media.interceptor;

import nyist.media.page.ApiResult;
import nyist.media.utils.RenderUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

import static nyist.media.constant.SystemConstant.UNAUTHORIZED_URL;

/**
 * @author : dcf
 * @date : 2019/3/12
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (SecurityUtils.getSubject().isAuthenticated()) {
            return true;
        }
        //跨域
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && "XMLHttpRequest".equalsIgnoreCase(requestType)) {
            response.addHeader("loginStatus", "accessDenied");
            RenderUtil.readJson(response, ApiResult.TO_LOGIN, null);
            return false;
        } else {
            if (request.getMethod().equalsIgnoreCase(HttpMethod.GET.name())) {
                String redirectUrl = request.getQueryString() != null
                        ? request.getRequestURI() + "?" + request.getQueryString()
                        : request.getRequestURI();
                response.sendRedirect(request.getContextPath() + UNAUTHORIZED_URL + "?redirectUrl="
                        + URLEncoder.encode(redirectUrl, "UTF-8"));
            } else {
                response.sendRedirect(request.getContextPath() + UNAUTHORIZED_URL);
            }
            return false;
        }
    }
}

